package com.crysta1.aitrans;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class HistoryActivity extends AppCompatActivity {

    private LinearLayout historyContainer;
    private DatabaseHelper dbHelper;
    private SharedPreferences prefs;
    private static final int MAX_DELETE_PER_DAY = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        historyContainer = findViewById(R.id.historyContainer);
        dbHelper = new DatabaseHelper(this);
        prefs = getSharedPreferences("history_prefs", MODE_PRIVATE);

        loadHistory();
    }

    private void loadHistory() {
        historyContainer.removeAllViews(); // 清空旧数据

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM quiz_records ORDER BY timestamp DESC", null);

        if (cursor.getCount() == 0) {
            TextView emptyView = new TextView(this);
            emptyView.setText("暂无答题记录");
            emptyView.setTextSize(16);
            emptyView.setPadding(0, 50, 0, 0);
            emptyView.setGravity(View.TEXT_ALIGNMENT_CENTER);
            historyContainer.addView(emptyView);
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String question = cursor.getString(1);
            String answer = cursor.getString(2);
            long timeSpent = cursor.getLong(3);
            float score = cursor.getFloat(4);
            String difficulty = cursor.getString(5);
            String aiResponse = cursor.getString(6);
            long timestamp = cursor.getLong(7);

            // 创建历史记录项视图
            View historyItem = getLayoutInflater().inflate(R.layout.item_history, null);

            TextView tvDate = historyItem.findViewById(R.id.tvDate);
            TextView tvDifficulty = historyItem.findViewById(R.id.tvDifficulty);
            TextView tvQuestion = historyItem.findViewById(R.id.tvQuestion);
            TextView tvAnswer = historyItem.findViewById(R.id.tvAnswer);
            TextView tvTime = historyItem.findViewById(R.id.tvTime);
            TextView tvScore = historyItem.findViewById(R.id.tvScore);

            // 设置数据
            tvDate.setText(dateFormat.format(new Date(timestamp)));
            tvDifficulty.setText("难度: " + getDifficultyText(difficulty));
            tvQuestion.setText(question);

            if (answer.isEmpty()) {
                tvAnswer.setText("用户答案: [放弃答题]");
            } else {
                tvAnswer.setText("用户答案: " + answer);
            }

            long minutes = timeSpent / 60;
            long seconds = timeSpent % 60;
            tvTime.setText(String.format(Locale.getDefault(), "用时: %02d:%02d", minutes, seconds));

            if (score == -1) {
                tvScore.setText("得分: 放弃");
                tvScore.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
            } else {
                tvScore.setText(String.format(Locale.getDefault(), "得分: %.2f/10", score));
                if (score >= 8) {
                    tvScore.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else if (score >= 6) {
                    tvScore.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
                } else {
                    tvScore.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                }
            }

            // 点击弹窗显示详细信息 + 删除功能
            historyItem.setOnClickListener(v -> showHistoryDetail(id, question, answer, timeSpent, score, difficulty, aiResponse, timestamp));

            historyContainer.addView(historyItem);
        }

        cursor.close();
    }

    private void showHistoryDetail(int id, String question, String answer, long timeSpent, float score,
                                   String difficulty, String aiResponse, long timestamp) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        long minutes = timeSpent / 60;
        long seconds = timeSpent % 60;

        View dialogView = getLayoutInflater().inflate(R.layout.dialog_history_detail, null);

        TextView tvQuestion = dialogView.findViewById(R.id.tvDialogQuestion);
        TextView tvAnswer = dialogView.findViewById(R.id.tvDialogAnswer);
        TextView tvTime = dialogView.findViewById(R.id.tvDialogTime);
        TextView tvScore = dialogView.findViewById(R.id.tvDialogScore);
        TextView tvDifficulty = dialogView.findViewById(R.id.tvDialogDifficulty);
        TextView tvAIResponse = dialogView.findViewById(R.id.tvDialogAIResponse);
        TextView tvTimestamp = dialogView.findViewById(R.id.tvDialogTimestamp);

        tvQuestion.setText("题目: " + question);
        tvAnswer.setText("用户答案: " + (answer.isEmpty() ? "[放弃答题]" : answer));
        tvTime.setText(String.format(Locale.getDefault(), "用时: %02d:%02d", minutes, seconds));
        tvScore.setText(score == -1 ? "得分: 放弃" : String.format(Locale.getDefault(), "得分: %.2f/10", score));
        tvDifficulty.setText("难度: " + getDifficultyText(difficulty));
        tvAIResponse.setText("AI 回复: " + aiResponse);
        tvTimestamp.setText(dateFormat.format(new Date(timestamp)));

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("答题记录详情")
                .setView(dialogView)
                .setPositiveButton("关闭", null)
                .setNegativeButton("删除", (dialog, which) -> {
                    if (canDeleteToday()) {
                        deleteRecord(id);
                    } else {
                        new AlertDialog.Builder(this)
                                .setTitle("提示")
                                .setMessage("每天最多删除 " + MAX_DELETE_PER_DAY + " 条记录")
                                .setPositiveButton("确定", null)
                                .show();
                    }
                })
                .show();
    }

    private boolean canDeleteToday() {
        String todayKey = getTodayKey();
        int deletedCount = prefs.getInt(todayKey, 0);
        return deletedCount < MAX_DELETE_PER_DAY;
    }

    private void incrementDeleteCount() {
        String todayKey = getTodayKey();
        int deletedCount = prefs.getInt(todayKey, 0);
        prefs.edit().putInt(todayKey, deletedCount + 1).apply();
    }

    private String getTodayKey() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        return "delete_count_" + year + month + day;
    }

    private void deleteRecord(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("quiz_records", "id=?", new String[]{String.valueOf(id)});
        incrementDeleteCount();
        loadHistory(); // 重新加载
    }

    private String getDifficultyText(String difficulty) {
        switch (difficulty) {
            case "E": return "简单";
            case "M": return "适中";
            case "H": return "困难";
            case "R": return "仿真";
            default: return "未知";
        }
    }
}
